'use strict';

function Changer(argument) {
    var path = argument.path;
    // var year = argument.year;
    // var month = argument.month;
    var count_date = null;
    var dataWaitWrite;

    var header = new Array();
    var XLSX = require('xlsx');

    var electron = require("electron");
    var dialog = electron.remote.dialog;

    var chager = {
        /**
         * 读取excel源文件
         * @return {[type]} [description]
         */
        do: function() {
            _readExcel(path);
        },
        /**
         * 保存新生成的excel
         * @return {[type]} [description]
         */
        save: function() {

            dialog.showOpenDialog({
                properties: [
                    'openDirectory',
                ]
            }, function(res) {
                _writeExcel({
                    data: dataWaitWrite,
                    path: res[0]
                });
            });
        },
        test: function(dom) {
            var _headers = ['id', 'name', 'age', 'country', 'remark'];
            var _data = [{
                id: '1',
                name: 'test1',
                age: '30',
                country: 'China',
                remark: 'hello'
            }, {
                id: '2',
                name: 'test2',
                age: '20',
                country: 'America',
                remark: 'world'
            }, {
                id: '3',
                name: 'test3',
                age: '18',
                country: 'Unkonw',
                remark: '???'
            }];
            var headers = _headers.map((v, i) => Object.assign({}, { v: v, position: String.fromCharCode(65 + i) + 1 }))
                .reduce((prev, next) => Object.assign({}, prev, {
                    [next.position]: { v: next.v }
                }), {});

            var data = _data
                .map((v, i) => _headers.map((k, j) => Object.assign({}, { v: v[k], position: String.fromCharCode(65 + j) + (i + 2) })))
                .reduce((prev, next) => prev.concat(next))
                .reduce((prev, next) => Object.assign({}, prev, {
                    [next.position]: { v: next.v }
                }), {});

            var output = Object.assign({}, headers, data);
            var outputPos = Object.keys(output);
            var ref = outputPos[0] + ':' + outputPos[outputPos.length - 1];
            var wb = {
                SheetNames: ['mySheet'],
                Sheets: {
                    'mySheet': Object.assign({}, output, { '!ref': ref })
                }
            };
            debugger;

            XLSX.writeFile(wb, __dirname + '/output.xlsx');

        }
    };

    /**
     * 读取excel的内容
     * 依赖xlsx模块
     * @param  {[type]} path [description]
     * @return {[type]}      [description]
     */
    function _readExcel( /*string*/ path) {
        var workbook = XLSX.readFile(path);
        var sheets = Object.getOwnPropertyNames(workbook.Sheets);
        if (sheets.length > 0) {
            var dataSheet = workbook.Sheets[sheets[0]];
            var o_data = XLSX.utils.sheet_to_json(dataSheet, { range: 2 });
            var n_data = new Array();
            var persons = new Array();

            for (var i = 0; i < o_data.length; i++) {
                //记录一下第一条记录的时间，作为系统的时间
                var row = o_data[i];
                var date = row['考勤时间'];
                var dd = date.split(' ');
                if (i == 0) {
                    count_date = dd[0];
                }
                persons.push(row['姓名']);

                n_data.push({
                    'name': row['姓名'],
                    'date': dd[0],
                    'time': dd[1]
                });
            }

            var pAs = _createPersonAttan(persons);
            for (var i = 0; i < n_data.length; i++) {
                var d = n_data[i];
                for (var j = 0; j < pAs.length; j++) {
                    var pa = pAs[j];
                    if (d.name == pa.name) {
                        var v = pa[d.date];
                        if (v == '-') {
                            v = d.time;
                        } else {
                            v += '\n' + d.time;
                        }
                        pa[d.date] = v;
                    }
                }
            }
            dataWaitWrite = pAs;
        }
    };



    /**
     * 写入excel
     * @param  {[type]} data [description]
     * @return {[type]}      [description]
     */
    function _writeExcel(arg) {
        debugger;
        var wb = _createWorkbook(arg.data);
        XLSX.writeFile(wb, arg.path + '/out.xlsx');
    };

    function Workbook() {
        if (!(this instanceof Workbook))
            return new Workbook();
        this.SheetNames = [];
        this.Sheets = {};
    };

    /**
     * 创建xlsx对象
     * @param  {[type]} data [description]
     * @return {[type]}      [description]
     */
    function _createWorkbook(data) {
        //创建一个符合格式的json就可以write了

        var excelTempData = new Array();
        var header = _createOutPutHeader(count_date);
        excelTempData.push(header);
        for (var i = 0; i < data.length; i++) {
            var d = data[i];
            var row = new Array();
            row.push(d.name);
            for (var j = 1; j < header.length; j++) {
                row.push(d[header[j]]);
            }

            excelTempData.push(row);
        }
        var ws = XLSX.utils.aoa_to_sheet(excelTempData);
        var wb = new Workbook();
        wb.SheetNames.push('sheet1');
        wb.Sheets['sheet1'] = ws;
        return wb;
    };

    /**
     * 创建输出用表头
     * @param  {[type]} date [description]
     * @return {[type]}      [description]
     */
    function _createOutPutHeader(date) {
        debugger;
        var ds = date.split('/');
        var header = new Array();
        header.push('姓名');
        var year = new Number(ds[0]).valueOf();
        var month = new Number(ds[1]).valueOf();
        var aM = [1, 3, 5, 7, 8, 10, 12];
        var bM = [4, 6, 9, 11];
        var length = -1;
        if (aM.indexOf(month) > -1) {
            length = 31;
        } else if (bM.indexOf(month) > -1) {
            length = 30
        } else {
            if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
                length = 29;
            } else {
                length = 28;
            }
        }
        var monthValue = month < 10 ? '0' + month : '' + month;

        for (var i = 1; i < length + 1; i++) {
            var day;
            if (i < 10) {
                day = '0' + i;
            } else {
                day = i;
            }
            var prop = year + '/' + monthValue + '/' + day;
            header.push(prop);
        }
        return header;
    };


    /**
     * 创建最后用来写excel的数据
     * @param  {[type]} pArray [description]
     * @return {[type]}        [description]
     */
    function _createPersonAttan(pArray) {
        var persons = new Set(pArray);
        var p = persons.values();
        var resultTemp = new Array();
        var a = p.next();

        while (a.value != undefined) {
            var new_row = _createCurrentMonthObj(a.value, count_date);
            resultTemp.push(new_row);
            a = p.next();
        }

        return resultTemp;
    };

    /**
     * 创建当前月份
     * @param  {[type]} name [description]
     * @param  {[type]} date [description]
     * @return {[type]}      [description]
     */
    function _createCurrentMonthObj(name, date) {
        var ds = count_date.split('/');
        debugger;
        var year = new Number(ds[0]).valueOf();
        var month = new Number(ds[1]).valueOf();
        var aM = [1, 3, 5, 7, 8, 10, 12];
        var bM = [4, 6, 9, 11];
        var length = -1;
        if (aM.indexOf(month) > -1) {
            length = 31;
        } else if (bM.indexOf(month) > -1) {
            length = 30
        } else {
            if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
                length = 29;
            } else {
                length = 28;
            }
        }
        var monthValue = month < 10 ? '0' + month : '' + month;
        var ob = new Object();
        ob.name = name;

        for (var i = 1; i < length + 1; i++) {
            var day;
            if (i < 10) {
                day = '0' + i;
            } else {
                day = i;
            }
            var prop = year + '/' + monthValue + '/' + day;
            Object.defineProperty(ob, prop, {
                __proto__: null,
                writable: true,
                value: '-'
            });
        }
        return ob;
    }

    return chager;
}
